<template>
  <div ref="wrapperEl" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <QuestSearch v-model:model="searchParams" @reset="getData" @search="getData" />
    <ACard
      title="面试问题列表"
      :bordered="false"
      :body-style="{ paddingTop: '0px' }"
      class="card-wrapper sm:flex-1-hidden"
    >
      <template #extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <ATable
        :columns="columns"
        :data-source="data"
        size="small"
        :scroll="{ x: 'max-content' }"
        :loading="loading"
        :row-selection="rowSelection"
        row-key="id"
        :pagination="pagination"
        class="h-full"
      />
    </ACard>
    <QuestOperateDrawer
      v-model:visible="drawerVisible"
      :operate-type="operateType"
      :row-data="editingData"
      @submitted="getData"
    />
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref } from 'vue';
import type { Ref } from 'vue';
import { Button, Popconfirm, Space, Tag, Modal } from 'ant-design-vue';
import { useTable, useTableOperate } from '@/hooks/common/table';
import {
  fetchGetQuestList,
  fetchDeleteQuest,
  fetchDeleteQuests,
  fetchChangeQuestStatus,
} from '@/service/api/system-manage';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { enableStatusRecord } from '@/constants/business';
import QuestOperateDrawer, { type OperateType } from './modules/quest-operate-drawer.vue';
import QuestSearch from './modules/quest-search.vue';

defineOptions({
  name: 'ManagePost'
});

const appStore = useAppStore();

const wrapperEl = ref<HTMLElement>();

const { columns, columnChecks, data, getData, getDataByPage, loading, pagination, reloadColumns, searchParams } =
  useTable({
    apiFn: fetchGetQuestList,
    apiParams: {
      current: 1,
      size: 10,
      questName: null,
      questCode: null,
      questDifficulty: null,
      status: null,
    },
    columns: () => [
      {
        key: 'selection',
        title: '',
        type: 'selection',
        align: 'center',
        width: 48,
        fixed: 'left'
      },
      {
        key: 'index',
        title: $t('common.index'),
        align: 'center',
        customRender: ({ index }) => index + 1
      },
      {
        key: 'questName',
        title: '问题分类',
        align: 'center',
        dataIndex: 'questName'
      },
      {
        key: 'questCode',
        title: '问题编号',
        align: 'center',
        dataIndex: 'questCode'
      },
      {
        key: 'questDifficulty',
        title: '问题难度',
        align: 'center',
        dataIndex: 'questDifficulty'
      },
      {
        key: 'questContent',
        title: '问题内容',
        align: 'center',
        dataIndex: 'questContent'
      },
      {
        key: 'status',
        title: '状态',
        align: 'center',
        dataIndex: 'status',
        customRender: ({ record }) => {
          if (record.status === null) {
            return null;
          }

          const label = $t(enableStatusRecord[record.status]);

          return <Tag color={record.status === 1 ? 'success' : 'error'}>{label}</Tag>;
        }
      },
      {
        key: 'createTime',
        title: '创建时间',
        align: 'center',
        dataIndex: 'createTime'
      },
      {
        key: 'remark',
        title: '备注',
        align: 'center',
        ellipsis: true,
        dataIndex: 'remark'
      },
      {
        key: 'operate',
        title: $t('common.operate'),
        align: 'center',
        fixed: 'right',
        customRender: ({ record }) => (
          <div class="flex-center gap-8px">
            <Button type="primary" ghost size="small" onClick={() => edit(record.id)}>
              {$t('common.edit')}
            </Button>
            <Button
              type={record.status === 1 ? 'default' : 'primary'}
              size="small"
              onClick={() => toggleStatus(record.id, record.status)}
            >
              {record.status === 1 ? '禁用' : '启用'}
            </Button>
            <Popconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.id)}>
              <Button danger size="small">
                {$t('common.delete')}
              </Button>
            </Popconfirm>
          </div>
        )
      }
    ]
  });

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted,
  rowSelection
} = useTableOperate(data, getData);

async function handleBatchDelete() {
  if (checkedRowKeys.value.length === 0) {
    window.$message?.warning('请选择要删除的岗位');
    return;
  }

  Modal.confirm({
    title: '批量删除问题',
    content: `确定要删除选中的 ${checkedRowKeys.value.length} 个问题吗？删除后无法恢复！`,
    okText: '确定',
    cancelText: '取消',
    async onOk() {
      try {
        const { error } = await fetchDeleteQuests(checkedRowKeys.value);
        if (!error) {
          onBatchDeleted();
        } else {
          window.$message?.error('批量删除失败: ' + error);
        }
      } catch (e) {
        window.$message?.error('操作失败: ' + e.message);
      }
    }
  });
}

async function handleDelete(id: number) {
  const { error } = await fetchDeleteQuest(id);
  if (!error) {
    onDeleted();
  }
}

async function toggleStatus(id: number, status: number) {
  const newStatus = status === 1 ? 0 : 1;
  const { error } = await fetchChangeQuestStatus(id, newStatus);
  if (!error) {
    window.$message?.success('状态修改成功');
    getData();
  }
}

function edit(id: number) {
  handleEdit(id);
}
</script>

<style scoped>
.card-wrapper {
  @apply flex-col-stretch gap-16px overflow-hidden;
}
</style>
